package lottery

import (
	"lottery/libs/myredis"
	"time"

	"gopkg.in/redis.v5"
)

type Cache interface {
	Set(string, string) error
	SetExp(string, string, time.Duration) error
	DefualtExp() time.Duration
	GetSet(string, string) (string, error)
	Get(string) (string, error)
	Del(string) error
}

type EmptyCache struct{}

func (e *EmptyCache) Set(string, string) error {
	return nil
}

func (e *EmptyCache) DefualtExp() time.Duration {
	return 0
}

func (e *EmptyCache) SetExp(string, string, time.Duration) error {
	return nil
}

func (e *EmptyCache) GetSet(string, string) (string, error) {
	return "", nil
}

func (e *EmptyCache) Get(string) (string, error) {
	return "", nil
}

func (e *EmptyCache) Del(string) error {
	return nil
}

type RedisCache struct {
	expiration time.Duration
	client     *redis.Client
}

func NewRedisCache() (cache *RedisCache) {
	client, err := myredis.OpenBase()
	if err != nil {
		panic(err)
	}

	return &RedisCache{
		expiration: time.Second * 10,
		client:     client,
	}
}

func (r *RedisCache) Set(key string, value string) (err error) {
	statusCmd := r.client.Set(key, value, r.expiration)
	return statusCmd.Err()
}

func (r *RedisCache) DefualtExp() time.Duration {
	return r.expiration
}

func (r *RedisCache) SetExp(key string, value string, exp time.Duration) (err error) {
	statusCmd := r.client.Set(key, value, exp)
	return statusCmd.Err()
}

func (r *RedisCache) GetSet(key string, value string) (oldValue string, err error) {
	stringCmd := r.client.GetSet(key, value)
	return stringCmd.Val(), stringCmd.Err()
}

func (r *RedisCache) Get(key string) (value string, err error) {
	stringCmd := r.client.Get(key)
	return stringCmd.Val(), stringCmd.Err()
}

func (r *RedisCache) Del(key string) error {
	intCmd := r.client.Del(key)
	return intCmd.Err()
}
